17. Using existing static classes¶
Note
The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.
These classes are reference libraries of methods and properties that do not change state, in one word, immutable.
You don't need to create them, you simply use them. Classes and methods such as these are called static classes because they are not created, destroyed, or changed. You can refer to a static class by surrounding the class name with square brackets.
17.1: Adding types¶
By Assembly Name, add library
1 | Add- Type - AssemblyName "System.Math" |
or by file path:
1 | Add- Type -Path "D:\Libs\CustomMath.dll" |
To Use added type:
1 | [CustomMath.NameSpace]::Method(param1, $variableParam, [int]castMeAsIntParam) |
17.2: Using the .Net Math Class¶
You can use the .Net Math class to do calculations ([System.Math])
If you want to know which methods are available you can use:
1 | [System.Math] | Get-Member -Static -MemberType Methods |
Here are some examples how to use the Math class:
1 2 3 4 5 6 7 8 | [System.Math]::Floor(9.42) 9 [System.Math]::Ceiling(9.42) 10 [System.Math]::Pow( 4 , 3 ) 64 [System.Math]::Sqrt( 49 ) 7 |
17.3: Creating new GUID instantly¶
Use existing .NET classes instantly with PowerShell by using [class]::Method(args):
1 | [guid]::NewGuid() |
1 2 3 | Guid ---- 8874a185-64be-43ed-a64c-d2fe4b6e31bc |
Similarly, in PowerShell 5+ you may use the New-Guid cmdlet:
1 | New-Guid
|
1 2 3 | Guid ---- 8874a185-64be-43ed-a64c-d2fe4b6e31bc |
To get the GUID as a [String] only, referenced the .Guid property:
1 | [guid]::NewGuid().Guid |